import React, { useState, useEffect } from 'react';
import api from '../services/api';
import { getToken } from '../utils/authUtils';
import './AdminDashboard.css'; // 我们将在这里添加新的CSS样式

const AdminDashboard = () => {
    const [users, setUsers] = useState([]);
    const [orders, setOrders] = useState([]);
    const [error, setError] = useState('');
    const [activeTab, setActiveTab] = useState('users');

    useEffect(() => {
        const fetchAdminData = async () => {
            try {
                const token = getToken();
                const config = {
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                };

                const [usersResponse, ordersResponse] = await Promise.all([
                    api.get('/admin/users', config),
                    api.get('/admin/orders', config)
                ]);

                setUsers(usersResponse.data);
                setOrders(ordersResponse.data);

            } catch (err) {
                console.error("Error fetching admin data", err.response?.data || err.message);
                setError('无法加载管理员数据，请确认您有管理员权限。');
            }
        };

        fetchAdminData();
    }, []);

    const handleDeleteUser = async (userId) => {
        if (window.confirm('您确定要删除该用户吗？此操作不可逆！')) {
            try {
                const token = getToken();
                await api.delete(`/admin/users/${userId}`, {
                    headers: { 'Authorization': `Bearer ${token}` }
                });
                setUsers(users.filter(user => user.id !== userId));
            } catch (err) {
                console.error('Error deleting user', err);
                setError('删除用户失败。');
            }
        }
    };

    const handleDeleteOrder = async (orderId) => {
        if (window.confirm('您确定要删除该订单吗？')) {
            try {
                const token = getToken();
                await api.delete(`/admin/orders/${orderId}`, {
                    headers: { 'Authorization': `Bearer ${token}` }
                });
                setOrders(orders.filter(order => order.id !== orderId));
            } catch (err) {
                console.error('Error deleting order', err);
                setError('删除订单失败。');
            }
        }
    };

    const formatDate = (dateString) => {
        if (!dateString) return 'N/A';
        const options = { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit' };
        return new Date(dateString).toLocaleString('zh-CN', options);
    };

    return (
        <div className="admin-dashboard">
            <aside className="admin-sidebar">
                <h2>管理后台</h2>
                <nav>
                    <ul>
                        <li className={activeTab === 'users' ? 'active' : ''} onClick={() => setActiveTab('users')}>
                            用户管理
                        </li>
                        <li className={activeTab === 'orders' ? 'active' : ''} onClick={() => setActiveTab('orders')}>
                            订单管理
                        </li>
                    </ul>
                </nav>
            </aside>
            <main className="admin-main-content">
                <header className="admin-header">
                    <h1>{activeTab === 'users' ? '用户列表' : '订单列表'}</h1>
                </header>

                {error && <p className="error-message">{error}</p>}

                {activeTab === 'users' && (
                    <div className="admin-card">
                        <table className="admin-table">
                            <thead>
                                <tr>
                                    <th>ID</th>
                                    <th>用户名</th>
                                    <th>邮箱</th>
                                    <th>角色</th>
                                    <th>操作</th>
                                </tr>
                            </thead>
                            <tbody>
                                {users.map(user => (
                                    <tr key={user.id}>
                                        <td>{user.id}</td>
                                        <td>{user.username}</td>
                                        <td>{user.email}</td>
                                        <td>{user.role}</td>
                                        <td>
                                            <button onClick={() => handleDeleteUser(user.id)} className="btn-delete">
                                                删除
                                            </button>
                                        </td>
                                    </tr>
                                ))}
                            </tbody>
                        </table>
                    </div>
                )}

                {activeTab === 'orders' && (
                    <div className="admin-card">
                        <table className="admin-table">
                            <thead>
                                <tr>
                                    <th>订单号</th>
                                    <th>电影</th>
                                    <th>影院</th>
                                    <th>座位</th>
                                    <th>总价</th>
                                    <th>状态</th>
                                    <th>创建时间</th>
                                    <th>操作</th>
                                </tr>
                            </thead>
                            <tbody>
                                {orders.map(order => (
                                    <tr key={order.id}>
                                        <td>{order.orderNumber}</td>
                                        <td>{order.movieTitle}</td>
                                        <td>{order.cinemaName}</td>
                                        <td>{order.seats}</td>
                                        <td>¥{order.totalPrice.toFixed(2)}</td>
                                        <td>{order.status}</td>
                                        <td>{formatDate(order.createdAt)}</td>
                                        <td>
                                            <button onClick={() => handleDeleteOrder(order.id)} className="btn-delete">
                                                删除
                                            </button>
                                        </td>
                                    </tr>
                                ))}
                            </tbody>
                        </table>
                    </div>
                )}
            </main>
        </div>
    );
};

export default AdminDashboard; 